import sys
import os
from pathlib import Path
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                              QPushButton, QLabel, QFileDialog, QLineEdit, QMessageBox,
                              QHBoxLayout, QSpinBox, QCheckBox, QProgressBar)
from PySide6.QtCore import Qt, QSettings
from PIL import Image

class ImageProcessor(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("图像批量处理工具")
        self.setMinimumSize(600, 400)
        
        # 初始化设置
        self.settings = QSettings('ImageProcessor', 'BatchProcessor')
        
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        
        # 目录选择区域
        dir_layout = QVBoxLayout()
        
        # 源目录选择
        source_dir_layout = QHBoxLayout()
        source_dir_layout.addWidget(QLabel("源目录:"))
        self.source_dir_path = QLineEdit()
        self.source_dir_path.setPlaceholderText("选择源目录...")
        self.source_dir_path.setReadOnly(True)
        last_source_dir = self.settings.value('last_source_dir', '')
        if last_source_dir:
            self.source_dir_path.setText(last_source_dir)
        source_dir_layout.addWidget(self.source_dir_path)
        source_dir_button = QPushButton("选择目录")
        source_dir_button.clicked.connect(self.select_source_directory)
        source_dir_layout.addWidget(source_dir_button)
        
        # 目标目录选择
        target_dir_layout = QHBoxLayout()
        target_dir_layout.addWidget(QLabel("目标目录:"))
        self.target_dir_path = QLineEdit()
        self.target_dir_path.setPlaceholderText("选择目标目录...")
        self.target_dir_path.setReadOnly(True)
        last_target_dir = self.settings.value('last_target_dir', '')
        if last_target_dir:
            self.target_dir_path.setText(last_target_dir)
        target_dir_layout.addWidget(self.target_dir_path)
        target_dir_button = QPushButton("选择目录")
        target_dir_button.clicked.connect(self.select_target_directory)
        target_dir_layout.addWidget(target_dir_button)
        
        # 保持输出目录与源目录一致的选项
        self.same_dir_option = QCheckBox("输出到源目录")
        self.same_dir_option.setChecked(self.settings.value('same_dir_option', True, type=bool))
        self.same_dir_option.stateChanged.connect(self.toggle_target_directory)
        
        # 添加到目录布局
        dir_layout.addLayout(source_dir_layout)
        dir_layout.addLayout(target_dir_layout)
        dir_layout.addWidget(self.same_dir_option)
        
        # 初始化时设置目标目录状态
        self.toggle_target_directory()
        
        # 图片拼接设置
        settings_layout = QVBoxLayout()
        
        # 顶部图片选择
        top_image_layout = QHBoxLayout()
        top_image_layout.addWidget(QLabel("顶部图片:"))
        self.top_image_path = QLineEdit()
        self.top_image_path.setPlaceholderText("选择要拼接的顶部图片...")
        self.top_image_path.setReadOnly(True)
        top_image_layout.addWidget(self.top_image_path)
        top_image_button = QPushButton("选择图片")
        top_image_button.clicked.connect(self.select_top_image)
        top_image_layout.addWidget(top_image_button)
        
        # 底部图片选择
        bottom_image_layout = QHBoxLayout()
        bottom_image_layout.addWidget(QLabel("底部图片:"))
        self.bottom_image_path = QLineEdit()
        self.bottom_image_path.setPlaceholderText("选择要拼接的底部图片...")
        self.bottom_image_path.setReadOnly(True)
        bottom_image_layout.addWidget(self.bottom_image_path)
        bottom_image_button = QPushButton("选择图片")
        bottom_image_button.clicked.connect(self.select_bottom_image)
        bottom_image_layout.addWidget(bottom_image_button)
        
        # 添加图片裁剪设置
        crop_settings = QVBoxLayout()
        crop_settings.addWidget(QLabel("图片裁剪设置:"))
        
        # 裁剪参数输入
        crop_params_layout = QHBoxLayout()
        
        # 左边距
        left_layout = QHBoxLayout()
        left_layout.addWidget(QLabel("左:"))
        self.crop_left = QSpinBox()
        self.crop_left.setRange(0, 1000)
        self.crop_left.setValue(0)
        left_layout.addWidget(self.crop_left)
        
        # 上边距
        top_layout = QHBoxLayout()
        top_layout.addWidget(QLabel("上:"))
        self.crop_top = QSpinBox()
        self.crop_top.setRange(0, 1000)
        self.crop_top.setValue(0)
        top_layout.addWidget(self.crop_top)
        
        # 右边距
        right_layout = QHBoxLayout()
        right_layout.addWidget(QLabel("右:"))
        self.crop_right = QSpinBox()
        self.crop_right.setRange(0, 1000)
        self.crop_right.setValue(0)
        right_layout.addWidget(self.crop_right)
        
        # 下边距
        bottom_layout = QHBoxLayout()
        bottom_layout.addWidget(QLabel("下:"))
        self.crop_bottom = QSpinBox()
        self.crop_bottom.setRange(0, 1000)
        self.crop_bottom.setValue(0)
        bottom_layout.addWidget(self.crop_bottom)
        
        # 添加所有裁剪参数到布局
        crop_params_layout.addLayout(left_layout)
        crop_params_layout.addLayout(top_layout)
        crop_params_layout.addLayout(right_layout)
        crop_params_layout.addLayout(bottom_layout)
        
        # 添加自动去除黑边选项
        self.auto_remove_black = QCheckBox("自动去除黑边")
        
        # 添加到裁剪设置布局
        crop_settings.addLayout(crop_params_layout)
        crop_settings.addWidget(self.auto_remove_black)
        
        # 添加图片压缩设置
        compress_settings = QVBoxLayout()
        compress_settings.addWidget(QLabel("图片压缩设置:"))
        
        # 添加是否压缩选项
        self.enable_compress = QCheckBox("启用压缩")
        compress_settings.addWidget(self.enable_compress)
        
        # 添加压缩分辨率设置
        resolution_layout = QHBoxLayout()
        resolution_layout.addWidget(QLabel("压缩分辨率:"))
        
        # 宽度设置
        width_layout = QHBoxLayout()
        width_layout.addWidget(QLabel("宽:"))
        self.compress_width = QSpinBox()
        self.compress_width.setRange(0, 10000)
        self.compress_width.setValue(1080)  # 默认值1080
        self.compress_width.setSuffix(" px")
        width_layout.addWidget(self.compress_width)
        
        # 高度设置
        height_layout = QHBoxLayout()
        height_layout.addWidget(QLabel("高:"))
        self.compress_height = QSpinBox()
        self.compress_height.setRange(0, 10000)
        self.compress_height.setValue(1080)  # 默认值1080
        self.compress_height.setSuffix(" px")
        height_layout.addWidget(self.compress_height)
        
        # 添加宽高设置到分辨率布局
        resolution_layout.addLayout(width_layout)
        resolution_layout.addLayout(height_layout)
        
        # 添加分辨率设置到压缩设置布局
        compress_settings.addLayout(resolution_layout)
        
        # 添加到主布局
        settings_layout.addLayout(top_image_layout)
        settings_layout.addLayout(bottom_image_layout)
        settings_layout.addLayout(crop_settings)
        settings_layout.addLayout(compress_settings)
        
        # 添加按钮布局
        buttons_layout = QHBoxLayout()
        
        # 拼接按钮
        merge_button = QPushButton("图片拼接")
        merge_button.clicked.connect(self.process_merge)
        buttons_layout.addWidget(merge_button)
        
        # 裁剪按钮
        crop_button = QPushButton("图片裁剪")
        crop_button.clicked.connect(self.process_crop)
        buttons_layout.addWidget(crop_button)
        
        # 添加组合处理按钮
        combined_button = QPushButton("裁剪并拼接")
        combined_button.clicked.connect(self.process_combined)
        buttons_layout.addWidget(combined_button)
        
        # 添加进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)  # 初始时隐藏进度条
        
        # 添加所有组件到主布局
        layout.addLayout(dir_layout)
        layout.addLayout(settings_layout)
        layout.addLayout(buttons_layout)  # 使用新的按钮布局
        layout.addWidget(self.progress_bar)  # 添加进度条到布局
        layout.addStretch()

    def select_source_directory(self):
        start_dir = self.settings.value('last_source_dir', '')
        directory = QFileDialog.getExistingDirectory(self, "选择源目录", start_dir)
        if directory:
            self.source_dir_path.setText(directory)
            self.settings.setValue('last_source_dir', directory)
            # 如果选择了保持输出目录与源目录一致，则更新目标目录
            if self.same_dir_option.isChecked():
                self.target_dir_path.setText(directory)
                self.settings.setValue('last_target_dir', directory)
    
    def select_target_directory(self):
        start_dir = self.settings.value('last_target_dir', '')
        directory = QFileDialog.getExistingDirectory(self, "选择目标目录", start_dir)
        if directory:
            self.target_dir_path.setText(directory)
            self.settings.setValue('last_target_dir', directory)
    
    def toggle_target_directory(self):
        # 如果选择了保持输出目录与源目录一致，则禁用目标目录选择
        is_same_dir = self.same_dir_option.isChecked()
        self.target_dir_path.setEnabled(not is_same_dir)
        self.target_dir_path.setReadOnly(True)  # 始终保持只读
        
        # 更新目标目录为源目录
        if is_same_dir and self.source_dir_path.text():
            self.target_dir_path.setText(self.source_dir_path.text())
        
        # 保存设置
        self.settings.setValue('same_dir_option', is_same_dir)

    def select_top_image(self):
        file_name, _ = QFileDialog.getOpenFileName(
            self,
            "选择顶部图片",
            "",
            "图片文件 (*.jpg *.jpeg *.png *.bmp)"
        )
        if file_name:
            self.top_image_path.setText(file_name)
            self.settings.setValue('last_top_image', file_name)

    def select_bottom_image(self):
        file_name, _ = QFileDialog.getOpenFileName(
            self,
            "选择底部图片",
            "",
            "图片文件 (*.jpg *.jpeg *.png *.bmp)"
        )
        if file_name:
            self.bottom_image_path.setText(file_name)
            self.settings.setValue('last_bottom_image', file_name)

    def closeEvent(self, event):
        self.settings.setValue('last_source_dir', self.source_dir_path.text())
        self.settings.setValue('last_target_dir', self.target_dir_path.text())
        self.settings.setValue('same_dir_option', self.same_dir_option.isChecked())
        self.settings.setValue('last_top_image', self.top_image_path.text())
        self.settings.setValue('last_bottom_image', self.bottom_image_path.text())
        # 保存压缩设置
        self.settings.setValue('enable_compress', self.enable_compress.isChecked())
        self.settings.setValue('compress_width', self.compress_width.value())
        self.settings.setValue('compress_height', self.compress_height.value())
        event.accept()

    def loadSettings(self):
        self.source_dir_path.setText(self.settings.value('last_source_dir', ''))
        self.target_dir_path.setText(self.settings.value('last_target_dir', ''))
        self.same_dir_option.setChecked(self.settings.value('same_dir_option', True, type=bool))
        self.top_image_path.setText(self.settings.value('last_top_image', ''))
        self.bottom_image_path.setText(self.settings.value('last_bottom_image', ''))
        # 加载压缩设置
        self.enable_compress.setChecked(self.settings.value('enable_compress', False, type=bool))
        self.compress_width.setValue(self.settings.value('compress_width', 1080, type=int))
        self.compress_height.setValue(self.settings.value('compress_height', 1080, type=int))

    def resize_image_if_needed(self, img):
        """根据压缩设置调整图片大小"""
        if self.enable_compress.isChecked():
            width = self.compress_width.value()
            height = self.compress_height.value()
            # 只有当宽度和高度都大于0时才进行压缩
            if width > 0 and height > 0:
                # 保持原始宽高比
                img_width, img_height = img.size
                ratio = min(width / img_width, height / img_height)
                new_width = int(img_width * ratio)
                new_height = int(img_height * ratio)
                return img.resize((new_width, new_height), Image.LANCZOS)
        return img

    def remove_black_borders(self, img):
        """自动去除图片黑边"""
        # 转换为灰度图
        gray = img.convert('L')
        # 获取图片数据
        data = list(gray.getdata())  # 转换为列表
        width, height = gray.size
        
        # 找到非黑色区域的边界
        threshold = 10  # 黑色阈值
        
        # 找到顶部边界
        top = 0
        for y in range(height):
            row = data[y * width : (y + 1) * width]  # 获取一行数据
            if any(p > threshold for p in row):
                top = y
                break
                
        # 找到底部边界
        bottom = height - 1
        for y in range(height - 1, -1, -1):
            row = data[y * width : (y + 1) * width]  # 获取一行数据
            if any(p > threshold for p in row):
                bottom = y
                break
                
        # 找到左边界
        left = 0
        for x in range(width):
            column = [data[i * width + x] for i in range(height)]  # 获取一列数据
            if any(p > threshold for p in column):
                left = x
                break
                
        # 找到右边界
        right = width - 1
        for x in range(width - 1, -1, -1):
            column = [data[i * width + x] for i in range(height)]  # 获取一列数据
            if any(p > threshold for p in column):
                right = x
                break
        
        # 裁剪图片
        return img.crop((left, top, right + 1, bottom + 1))

    def get_edge_color(self, img, side='left'):
        """获取图片边缘的主要颜色"""
        if side == 'left':
            # 获取左边缘的像素
            edge_pixels = [img.getpixel((0, y)) for y in range(img.height)]
        else:
            # 获取右边缘的像素
            edge_pixels = [img.getpixel((img.width-1, y)) for y in range(img.height)]
        
        # 计算平均颜色
        r = sum(p[0] for p in edge_pixels) // len(edge_pixels)
        g = sum(p[1] for p in edge_pixels) // len(edge_pixels)
        b = sum(p[2] for p in edge_pixels) // len(edge_pixels)
        
        return (r, g, b)

    def get_edge_color_for_section(self, img, y_start, y_end, side='left', segment_height=50):
        """获取指定区域边缘的平均颜色，使用分段计算"""
        colors = []
        current_y = y_start
        
        # 分段计算平均颜色
        while current_y < y_end:
            segment_end = min(current_y + segment_height, y_end)
            if side == 'left':
                edge_pixels = [img.getpixel((0, y)) for y in range(current_y, segment_end)]
            else:
                edge_pixels = [img.getpixel((img.width-1, y)) for y in range(current_y, segment_end)]
            
            r = sum(p[0] for p in edge_pixels) // len(edge_pixels)
            g = sum(p[1] for p in edge_pixels) // len(edge_pixels)
            b = sum(p[2] for p in edge_pixels) // len(edge_pixels)
            
            colors.append((r, g, b, current_y, segment_end))
            current_y = segment_end
        
        return colors

    def interpolate_color(self, color1, color2, ratio):
        """在两个颜色之间进行插值"""
        return (
            int(color1[0] * (1 - ratio) + color2[0] * ratio),
            int(color1[1] * (1 - ratio) + color2[1] * ratio),
            int(color1[2] * (1 - ratio) + color2[2] * ratio)
        )

    def add_borders_for_square(self, img, top_height=0, bottom_height=0):
        """添加边框使图片成为正方形，考虑拼接区域"""
        width, height = img.size
        
        if width == height:
            return img
        
        # 计算需要添加的边框宽度
        target_size = max(width, height)
        total_border_width = target_size - width
        left_border = total_border_width // 2
        right_border = total_border_width - left_border
        
        # 创建新图片
        new_img = Image.new('RGB', (target_size, height), 'white')
        
        # 计算主图区域的位置
        main_start = top_height
        main_end = height - bottom_height if bottom_height > 0 else height
        
        # 获取分段的边缘颜色
        left_colors = self.get_edge_color_for_section(img, main_start, main_end, 'left')
        right_colors = self.get_edge_color_for_section(img, main_start, main_end, 'right')
        
        # 填充左边框
        for x in range(left_border):
            # 处理顶部拼接区域
            if top_height > 0:
                for y in range(top_height):
                    source_color = img.getpixel((0, y))
                    new_img.putpixel((x, y), source_color)
            
            # 处理主图区域 - 使用平滑过渡
            x_ratio = x / left_border  # 用于水平方向的颜色过渡
            for i, color_info in enumerate(left_colors):
                color = color_info[0:3]  # 获取RGB颜色值
                y_start = color_info[3]
                y_end = color_info[4]
                
                # 获取下一个颜色段用于垂直过渡
                next_color = left_colors[i+1][0:3] if i < len(left_colors)-1 else color
                
                for y in range(y_start, y_end):
                    # 计算垂直方向的过渡比例
                    y_ratio = (y - y_start) / (y_end - y_start)
                    # 在当前段内进行垂直插值
                    segment_color = self.interpolate_color(color, next_color, y_ratio)
                    # 水平方向的颜色过渡
                    final_color = self.interpolate_color(segment_color, img.getpixel((0, y)), x_ratio)
                    new_img.putpixel((x, y), final_color)
            
            # 处理底部拼接区域
            if bottom_height > 0:
                for y in range(main_end, height):
                    source_color = img.getpixel((0, y))
                    new_img.putpixel((x, y), source_color)
        
        # 粘贴原图
        new_img.paste(img, (left_border, 0))
        
        # 填充右边框
        for x in range(width + left_border, target_size):
            # 处理顶部拼接区域
            if top_height > 0:
                for y in range(top_height):
                    source_color = img.getpixel((width-1, y))
                    new_img.putpixel((x, y), source_color)
            
            # 处理主图区域 - 使用平滑过渡
            x_ratio = (x - (width + left_border)) / right_border
            for i, color_info in enumerate(right_colors):
                color = color_info[0:3]  # 获取RGB颜色值
                y_start = color_info[3]
                y_end = color_info[4]
                
                # 获取下一个颜色段用于垂直过渡
                next_color = right_colors[i+1][0:3] if i < len(right_colors)-1 else color
                
                for y in range(y_start, y_end):
                    y_ratio = (y - y_start) / (y_end - y_start)
                    segment_color = self.interpolate_color(color, next_color, y_ratio)
                    final_color = self.interpolate_color(img.getpixel((width-1, y)), segment_color, x_ratio)
                    new_img.putpixel((x, y), final_color)
            
            # 处理底部拼接区域
            if bottom_height > 0:
                for y in range(main_end, height):
                    source_color = img.getpixel((width-1, y))
                    new_img.putpixel((x, y), source_color)
        
        return new_img

    def process_merge(self):
        """进行图片拼接处理"""
        source_dir_path = self.source_dir_path.text()
        target_dir_path = self.target_dir_path.text()
        top_image_path = self.top_image_path.text()
        bottom_image_path = self.bottom_image_path.text()
        
        if not source_dir_path:
            QMessageBox.warning(self, "警告", "请选择源目录！")
            return
        
        if not target_dir_path:
            QMessageBox.warning(self, "警告", "请选择目标目录！")
            return
            
        try:
            # 加载拼接用的图片
            top_image = None
            bottom_image = None
            if top_image_path:
                top_image = Image.open(top_image_path)
            if bottom_image_path:
                bottom_image = Image.open(bottom_image_path)
            
            source_path = Path(source_dir_path)
            target_path = Path(target_dir_path)
            
            # 确保目标目录存在
            target_path.mkdir(exist_ok=True)
            
            image_extensions = ['.jpg', '.jpeg', '.png', '.bmp']
            
            # 计算总任务数量
            total_files = sum(1 for f in source_path.iterdir() if f.suffix.lower() in image_extensions)
            
            # 初始化进度条
            self.progress_bar.setRange(0, total_files)
            self.progress_bar.setValue(0)
            self.progress_bar.setVisible(True)
            
            processed_count = 0
            
            for image_file in source_path.iterdir():
                if image_file.suffix.lower() in image_extensions:
                    with Image.open(image_file) as img:
                        if img.mode != 'RGB':
                            img = img.convert('RGB')
                        
                        # 计算拼接区域的高度
                        top_height = top_image.height if top_image else 0
                        bottom_height = bottom_image.height if bottom_image else 0
                        
                        # 计算最终图片的尺寸
                        total_height = img.height
                        if top_image:
                            total_height += top_image.height
                        if bottom_image:
                            total_height += bottom_image.height
                        
                        # 创建新图片
                        final_image = Image.new('RGB', (img.width, total_height), 'white')
                        current_y = 0
                        
                        # 拼接顶部图片
                        if top_image:
                            resized_top = top_image.resize((img.width, top_image.height))
                            final_image.paste(resized_top, (0, current_y))
                            current_y += top_image.height
                        
                        # 粘贴主图片
                        final_image.paste(img, (0, current_y))
                        current_y += img.height
                        
                        # 拼接底部图片
                        if bottom_image:
                            resized_bottom = bottom_image.resize((img.width, bottom_image.height))
                            final_image.paste(resized_bottom, (0, current_y))
                        
                        # 添加边框时传入拼接区域的高度
                        final_image = self.add_borders_for_square(
                            final_image, 
                            top_height=top_height,
                            bottom_height=bottom_height
                        )
                        
                        # 应用压缩设置
                        final_image = self.resize_image_if_needed(final_image)
                        
                        # 保存处理后的图片
                        file_stem = image_file.stem
                        file_suffix = image_file.suffix
                        new_filename = f"{file_stem}-merged{file_suffix}"
                        output_file = target_path / new_filename
                        final_image.save(output_file, quality=95)
                        processed_count += 1
                        
                        # 更新进度条
                        self.progress_bar.setValue(processed_count)
                        QApplication.processEvents()  # 确保UI更新
            
            # 处理完成后隐藏进度条
            self.progress_bar.setVisible(False)
            QMessageBox.information(self, "完成", f"成功拼接 {processed_count} 张图片！")
            
        except Exception as e:
            # 发生错误时隐藏进度条
            self.progress_bar.setVisible(False)
            QMessageBox.critical(self, "错误", f"处理图片时发生错误：{str(e)}")

    def process_crop(self):
        """只进行图片裁剪处理"""
        source_dir_path = self.source_dir_path.text()
        target_dir_path = self.target_dir_path.text()
        
        if not source_dir_path:
            QMessageBox.warning(self, "警告", "请选择源目录！")
            return
            
        if not target_dir_path:
            QMessageBox.warning(self, "警告", "请选择目标目录！")
            return
            
        try:
            source_path = Path(source_dir_path)
            target_path = Path(target_dir_path)
            
            # 确保目标目录存在
            target_path.mkdir(exist_ok=True)
            
            image_extensions = ['.jpg', '.jpeg', '.png', '.bmp']
            
            # 计算总任务数量
            total_files = sum(1 for f in source_path.iterdir() if f.suffix.lower() in image_extensions)
            
            # 初始化进度条
            self.progress_bar.setRange(0, total_files)
            self.progress_bar.setValue(0)
            self.progress_bar.setVisible(True)
            
            processed_count = 0
            
            for image_file in source_path.iterdir():
                if image_file.suffix.lower() in image_extensions:
                    with Image.open(image_file) as img:
                        if img.mode != 'RGB':
                            img = img.convert('RGB')
                        
                        processed_img = img
                        
                        # 应用裁剪
                        if any([self.crop_left.value(), self.crop_top.value(),
                               self.crop_right.value(), self.crop_bottom.value()]):
                            width, height = processed_img.size
                            processed_img = processed_img.crop((
                                self.crop_left.value(),
                                self.crop_top.value(),
                                width - self.crop_right.value(),
                                height - self.crop_bottom.value()
                            ))
                        
                        # 自动去除黑边
                        if self.auto_remove_black.isChecked():
                            processed_img = self.remove_black_borders(processed_img)
                        
                        # 应用压缩设置
                        processed_img = self.resize_image_if_needed(processed_img)
                        
                        # 保存处理后的图片
                        file_stem = image_file.stem
                        file_suffix = image_file.suffix
                        new_filename = f"{file_stem}-cropped{file_suffix}"
                        output_file = target_path / new_filename
                        processed_img.save(output_file, quality=95)
                        processed_count += 1
                        
                        # 更新进度条
                        self.progress_bar.setValue(processed_count)
                        QApplication.processEvents()  # 确保UI更新
            
            # 处理完成后隐藏进度条
            self.progress_bar.setVisible(False)
            QMessageBox.information(self, "完成", f"成功裁剪 {processed_count} 张图片！")
            
        except Exception as e:
            # 发生错误时隐藏进度条
            self.progress_bar.setVisible(False)
            QMessageBox.critical(self, "错误", f"处理图片时发生错误：{str(e)}")

    def process_combined(self):
        """先裁剪后拼接"""
        source_dir_path = self.source_dir_path.text()
        target_dir_path = self.target_dir_path.text()
        top_image_path = self.top_image_path.text()
        bottom_image_path = self.bottom_image_path.text()
        
        if not source_dir_path:
            QMessageBox.warning(self, "警告", "请选择源目录！")
            return
            
        if not target_dir_path:
            QMessageBox.warning(self, "警告", "请选择目标目录！")
            return
            
        try:
            source_path = Path(source_dir_path)
            target_path = Path(target_dir_path)
            
            # 确保目标目录存在
            target_path.mkdir(exist_ok=True)
            
            image_extensions = ['.jpg', '.jpeg', '.png', '.bmp']
            
            # 计算总任务数量
            total_files = sum(1 for f in source_path.iterdir() if f.suffix.lower() in image_extensions)
            
            # 初始化进度条
            self.progress_bar.setRange(0, total_files)
            self.progress_bar.setValue(0)
            self.progress_bar.setVisible(True)
            
            processed_count = 0
            
            # 加载拼接用的图片
            top_image = None
            bottom_image = None
            if top_image_path:
                top_image = Image.open(top_image_path)
            if bottom_image_path:
                bottom_image = Image.open(bottom_image_path)
            
            for image_file in source_path.iterdir():
                if image_file.suffix.lower() in image_extensions:
                    with Image.open(image_file) as img:
                        if img.mode != 'RGB':
                            img = img.convert('RGB')
                        
                        # 第一步：裁剪处理
                        processed_img = img
                        
                        # 应用裁剪
                        if any([self.crop_left.value(), self.crop_top.value(),
                               self.crop_right.value(), self.crop_bottom.value()]):
                            width, height = processed_img.size
                            processed_img = processed_img.crop((
                                self.crop_left.value(),
                                self.crop_top.value(),
                                width - self.crop_right.value(),
                                height - self.crop_bottom.value()
                            ))
                        
                        # 自动去除黑边
                        if self.auto_remove_black.isChecked():
                            processed_img = self.remove_black_borders(processed_img)
                        
                        # 第二步：拼接处理
                        # 计算最终图片的尺寸
                        total_height = processed_img.height
                        if top_image:
                            total_height += top_image.height
                        if bottom_image:
                            total_height += bottom_image.height
                        
                        # 创建新图片
                        final_image = Image.new('RGB', (processed_img.width, total_height), 'white')
                        current_y = 0
                        
                        # 拼接顶部图片
                        if top_image:
                            resized_top = top_image.resize((processed_img.width, top_image.height))
                            final_image.paste(resized_top, (0, current_y))
                            current_y += top_image.height
                        
                        # 粘贴处理后的主图片
                        final_image.paste(processed_img, (0, current_y))
                        current_y += processed_img.height
                        
                        # 拼接底部图片
                        if bottom_image:
                            resized_bottom = bottom_image.resize((processed_img.width, bottom_image.height))
                            final_image.paste(resized_bottom, (0, current_y))
                        
                        # 应用压缩设置
                        final_image = self.resize_image_if_needed(final_image)
                        
                        # 保存处理后的图片
                        file_stem = image_file.stem
                        file_suffix = image_file.suffix
                        new_filename = f"{file_stem}-combined{file_suffix}"
                        output_file = target_path / new_filename
                        final_image.save(output_file, quality=95)
                        processed_count += 1
            
            # 更新进度条
            self.progress_bar.setValue(processed_count)
            QApplication.processEvents()  # 确保UI更新
            
            # 处理完成后隐藏进度条
            self.progress_bar.setVisible(False)
            QMessageBox.information(self, "完成", f"成功处理 {processed_count} 张图片！")
            
        except Exception as e:
            # 发生错误时隐藏进度条
            self.progress_bar.setVisible(False)
            QMessageBox.critical(self, "错误", f"处理图片时发生错误：{str(e)}")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ImageProcessor()
    window.show()
    sys.exit(app.exec())